﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class Admin_Sanpham : System.Web.UI.Page
{
    DADataContext da = new DADataContext();
    XL kn = new XL();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (string.IsNullOrEmpty(Convert.ToString(Session["user"])))
            {
                Response.Redirect("/Online/Dangnhap/");
            }
            else
            {
                var mcn = (from cn in da.Chucnangs where cn.Tenchucnang == "Quản lý sản phẩm" select cn.Machucnang).FirstOrDefault();
                var kt = (from a in da.TaikhoanChucnangs where (a.Taikhoan == Session["user"].ToString() && a.Machucnang == mcn) select a).Count();
                if (kt == 1)
                {
                    if (string.IsNullOrEmpty(Convert.ToString(Request.QueryString["do"])) && string.IsNullOrEmpty(Convert.ToString(Request.QueryString["m"])))
                    {
                        LoadDropHSX(dlhangsx);

                        pnht.Visible = true;
                        pnThemsp.Visible = false;
                        pnEdit.Visible = false;
                        LoadGV();
                    }
                    else
                    {
                        if (string.IsNullOrEmpty(Convert.ToString(Request.QueryString["do"])))
                        {
                            int ma = int.Parse(Request.QueryString["m"]);
                            var laytt = (from c in da.Sanphams where c.Masp == ma select c).FirstOrDefault();
                            fckttspedit.Value = laytt.Thongtinsp;
                            dlNCCedit.SelectedValue = laytt.MaNCC.ToString();
                            dlhsxedit.SelectedValue = laytt.Mahang.ToString();
                            txttenspedit.Text = laytt.Tensp;
                            txtsledit.Text = laytt.Soluong.ToString();
                            txtgianhapedit.Text = laytt.Gianhap.ToString();
                            txttinhangedit.Text = laytt.TinhnangNB;
                            txtkmedit.Text = laytt.Khuyenmai;
                            if (laytt.Hienthi == 1)
                                htedit.Checked = true;
                            else khtedit.Checked = true;
                            LoadDropHSX(dlhsxedit);
                            LoadDropNCC(dlNCCedit);
                            pnThemsp.Visible = false;
                            pnht.Visible = false;
                            pnEdit.Visible = true;

                        }
                        else
                        {
                            LoadDropHSX(dlHang);
                            LoadDropNCC(dlNCC);
                            pnThemsp.Visible = true;
                            pnht.Visible = false;
                            pnEdit.Visible = false;
                        }
                    }
                }
                else
                {
                    Response.Redirect("/Online/Admin/Default.aspx");
                }
            }
        }
    }
    void LoadDropHSX(DropDownList hsx)
    {
        var loaddrop = from a in da.HangSXes orderby a.Tenhang descending select a;
        hsx.DataSource = loaddrop;
        hsx.DataBind();
    }
    void LoadDropNCC(DropDownList ncc)
    {
        var loadncc = from a in da.NCCs orderby a.TenNCC ascending select new { a.MaNCC, a.TenNCC };
        ncc.DataSource = loadncc;
        ncc.DataBind();
    }
    protected void Themspmoi_Click(object sender, EventArgs e)
    {
        Response.Redirect("/Online/Admin/Sanpham.aspx?do=new");
    }
    protected void btnThem_Click(object sender, EventArgs e)
    {
        try
        {
            if (txttensp.Text == "" || txtsl.Text == "" || txtgianhap.Text == "" || txttinhnang.Text == "" || fckttsp.Value == "")
            {
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), " ", "alert('Nhập đủ thông tin trên !')", true);
            }
            else
            {

                int ncc = int.Parse(dlNCC.SelectedValue);
                int hsx = int.Parse(dlHang.SelectedValue);
                string tensp = txttensp.Text.Trim();
                string alisa=kn.ConvertToUnSign(txttensp.Text.Trim());
                int sl = int.Parse(txtsl.Text);
                float gianhap = float.Parse(txtgianhap.Text);
                string tinhnang = txttinhnang.Text;
                string ttsp = fckttsp.Value;
                string km = txtkm.Text;
                string ha = hinhanh.HasFile ? "/Online/Admin/Sanpham/Anhnho/" + hinhanh.FileName : "/Online/Admin/Sanpham/Anhnho/no-image.png";
                string anhto = hinhanhto.HasFile? "/Online/Admin/Sanpham/Anhto/" + hinhanhto.FileName:"/Online/Admin/Sanpham/Anhto/no-image.png";

                DateTime dt = DateTime.Parse(System.DateTime.Now.ToShortDateString() + " " + System.DateTime.Now.ToLongTimeString());
                int hthi = 0;
                if (ht.Checked == true) hthi = 1;
                else hthi = 0;
                Sanpham sp = new Sanpham();
                sp.MaNCC = ncc;
                sp.Mahang = hsx;
                sp.Tensp = tensp;
                sp.Alisa=alisa;
                sp.Soluong = sl;
                sp.Gianhap = gianhap;
                sp.TinhnangNB = tinhnang;
                sp.Thongtinsp = ttsp;
                sp.Khuyenmai = km;
                sp.Hinhanh = ha;
                sp.Anhto = anhto;
                sp.Ngaynhap = dt;
                sp.Hienthi = hthi;
                da.Sanphams.InsertOnSubmit(sp);
                da.SubmitChanges();
                if(hinhanh.HasFile)
                    hinhanh.SaveAs(Server.MapPath(ha));
                if(hinhanhto.HasFile)
                    hinhanhto.SaveAs(Server.MapPath(anhto));

                Reset();
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), " ", "alert('Lưu thành công !')", true);
                

            }
        }
        catch (Exception ax)
        {
            tb.Text = ax.Message;
        }
    }
    protected void btnHuy_Click(object sender, EventArgs e)
    {
        Response.Redirect("/Online/Admin/Sanpham.aspx");
    }
    void Reset()
    {
        txttensp.Text = "";
        txtsl.Text = "";
        txtgianhap.Text = "";
        txttinhnang.Text = "";
        txtkm.Text = "";
        fckttsp.Value = "";
    }
    void Reset1()
    {
        txttenspedit.Text = "";
        txtsledit.Text = "";
        txtgianhapedit.Text = "";
        txttinhangedit.Text = "";
        txtkmedit.Text = "";
        fckttspedit.Value = "";
    }
    protected void btnSuaedit_Click(object sender, EventArgs e)
    {
        try
        {
            if (txttenspedit.Text == "" || txtsledit.Text == "" || txtgianhapedit.Text == "" || txttinhangedit.Text == "" || fckttspedit.Value == "")
            {
                Label1.Text = "Nhập đủ thông tin trên.";
            }
            else
            {
                int ma = int.Parse(Request.QueryString["m"]);
                int ncc = int.Parse(dlNCCedit.SelectedValue);
                int hsx = int.Parse(dlhsxedit.SelectedValue);
                string tensp = txttenspedit.Text.Trim();
                string alisa = kn.ConvertToUnSign(txttenspedit.Text.Trim());
                int sl = int.Parse(txtsledit.Text);
                float gianhap = float.Parse(txtgianhapedit.Text);
                string tinhnang = txttinhangedit.Text;
                string ttsp = fckttspedit.Value;
                string km = txtkmedit.Text;
                int hthi = 0;
                if (htedit.Checked == true) hthi = 1;
                else hthi = 0;

                var sp = (from b in da.Sanphams where b.Masp == ma select b).Single();

                sp.MaNCC = ncc;
                sp.Mahang = hsx;
                sp.Tensp = tensp;
                sp.Alisa = alisa;
                sp.Soluong = sl;
                sp.Gianhap = gianhap;
                sp.TinhnangNB = tinhnang;
                sp.Thongtinsp = ttsp;
                sp.Khuyenmai = km;
                sp.Hienthi = hthi;
                da.SubmitChanges();
                Response.Redirect("/Online/Admin/Sanpham.aspx");
            }
        }
        catch (Exception ax)
        {
            Label1.Text = ax.Message;
        }
    }
    protected void btnHuyedit_Click(object sender, EventArgs e)
    {
        Response.Redirect("/Online/Admin/Sanpham.aspx");
    }
    protected void dlhangsx_SelectedIndexChanged(object sender, EventArgs e)
    {
        LoadGV();   
    }
    void LoadGV()
    {
        int mahang = int.Parse(dlhangsx.SelectedValue);
        var loadGV = from b in da.Sanphams where b.Mahang == mahang orderby b.Tensp ascending select new { b.Masp, b.Tensp, b.Soluong, b.Hinhanh, b.Giaban };
        GVSP.DataSource = loadGV;
        GVSP.DataBind();
    }
    protected void btnTim_Click(object sender, EventArgs e)
    {
        string key = timkiem.Text;
        var search = (from y in da.Sanphams where y.Hienthi == 1 && y.Tensp.Contains(key) orderby y.Ngaynhap descending select y);
        GVSP.DataSource = search;
        GVSP.DataBind();
    }
    protected void GVSP_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        string id=e.CommandArgument.ToString();
        var check = from x in da.ChiTietDHs where x.IDSanPham.Equals(id) select x;
        if (check.Count() > 0)
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), " ", "alert('Sản phẩm đang nằm trong đơn đặt hàng, không thể xóa')", true);
        else
        {
            var del = (from y in da.Sanphams where y.Masp.Equals(id) select y).FirstOrDefault();
            da.Sanphams.DeleteOnSubmit(del);
            da.SubmitChanges();
            LoadGV();
        }
    }
}
